package com.brkj.course;


import java.io.File;
import java.util.List;


import android.os.Environment;
import com.brkj.main.R;
import com.brkj.util.ConstAnts;
import com.brkj.util.Util;
import com.brkj.util.view.BaseActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;
import android.webkit.WebSettings.PluginState;
import com.dgl.sdk.util.FileCache;


public class WebViewActivity extends BaseActivity implements OnGestureListener {

	private WebView web_view;
	private String url;
	private View titleView;
	
	private final Handler handler = new Handler();
	private GestureDetector gestureScanner;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
//		clearCookie();
		getData();
		initView();
		
		
	    gestureScanner = new GestureDetector(this);   
	    gestureScanner.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener(){  
	      public boolean onDoubleTap(MotionEvent e) {  
	        //双击时产生一次
	    	if(titleView.isShown()){
	    		titleView.setVisibility(View.GONE);
	    	}else{
	    		titleView.setVisibility(View.VISIBLE);
	    	}
	    	//返回为true 事件不在传递
	        return true;  
	      }
	      public boolean onDoubleTapEvent(MotionEvent e) {  
	        //双击时产生两次
	        return false;
	      }  
	      public boolean onSingleTapConfirmed(MotionEvent e) {  
	        //短快的点击算一次单击
	    	  
	        return false;  
	      }  
	    }); 
	    
	    web_view.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return gestureScanner.onTouchEvent(arg1);
			}
		});
	}
	private void clearCookie(){
		//经过查资料和stream指导，发现在用CookieManager操作Cookie前需要进行Cookie同步，只要在CookieManager.getInstance().setCookie(serverName, "")前添加如下代码，问题便可解决：
		try {
			CookieSyncManager.createInstance(this);
			CookieSyncManager.getInstance().startSync();
			CookieManager.getInstance().removeAllCookie();
			CookieManager.getInstance().removeExpiredCookie();
			CookieManager.getInstance().removeSessionCookie();
			WebViewDatabase.getInstance(this).clearUsernamePassword();
			WebViewDatabase.getInstance(this).clearHttpAuthUsernamePassword();
		} catch (Exception e) {
			// TODO: handle exception
		} catch(Error er){

		}
	}
	private void getData() {
		Intent intent = getIntent();
		url = intent.getStringExtra("url");

       //判断是不是已下载课程
        File file = new File(ConstAnts.DOWNLOAD_COURSE__DIR, FileCache.urlToFileName(url)+"url");

        if((file.exists()) && file.isDirectory()){
            url = file.getAbsolutePath()+"/index.html";
        }
	}

	private void initView() {
		setActivityTitle("课程内容");
		setReturnBtn();
		
		titleView = findViewById(R.id.titleView);
		titleView.setVisibility(View.GONE);
		
		web_view = (WebView) findViewById(R.id.webView);
		loadWeb();
		
		
	}

	@SuppressLint("NewApi")
	private void loadWeb() {
		
		WebSettings setting=web_view.getSettings();
		setting.setPluginState(PluginState.ON);
		setting.setJavaScriptEnabled(true);
		
		setting.setUseWideViewPort(true);
//		setting.setBuiltInZoomControls(true);
		setting.setSupportZoom(true);
		setting.setLoadWithOverviewMode(true);
		setting.setDefaultTextEncodingName("utf-8");

		if (url != null && !url.equals("")) {
//            url = Environment
//                    .getExternalStorageDirectory() + "/brkj/1/index.html";
//            url = "file://" + ConstAnts.IMG_CATCH_DIR + "/index.html";
			web_view.loadUrl(url);
//			web_view.loadUrl("http://html5test.com/");
//			web_view.loadUrl("http://118.192.9.79:85/3g/page1501.html");
//			web_view.loadUrl("http://118.192.9.79:85/energysaving/index.html");
/*		检测是否安装有flash插件	
			if(check()){
//				String url="file:///android_asset/a.swf";
//				String url="http://118.192.9.79:99/html";
//				String url="http://118.192.9.79:85/ROI1/";
				web_view.loadUrl(url);
			}else{
				install();
			}
			*/
		}
		
		web_view.setWebViewClient(new WebViewClient() {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if((url!= null) && (url.equals(""))){
				web_view.loadUrl(url);
			}else{
				return false;
			}
			
			return true;
		}
	});
		
	}

	
	private boolean check() {
		PackageManager pm = getPackageManager();
		List<PackageInfo> infoList = pm
				.getInstalledPackages(PackageManager.GET_SERVICES);
		for (PackageInfo info : infoList) {
			if ("com.adobe.flashplayer".equals(info.packageName)) {
				return true;
			}
		}
		return false;
	}
	
	private class AndroidBridge {
		public void goMarket() {
			handler.post(new Runnable() {
				public void run() {
					Intent installIntent = new Intent(
							"android.intent.action.VIEW");
					installIntent.setData(Uri
							.parse("market://details?id=com.adobe.flashplayer"));
					startActivity(installIntent);
				}
			});
		}
	}
	@SuppressLint("JavascriptInterface")
	private void install() {
		web_view.addJavascriptInterface(new AndroidBridge(), "android");
		web_view.loadUrl("file:///android_asset/go_market.html");
	}

	public void onPause() {
		super.onPause();
		web_view.onPause();
	}
	
	public void onResume() {//继承自Activity
		super.onResume();
		web_view.onResume();
	}
	
	@Override
	public void finish() {
		
		//停止播放flash
//		web_view.pauseTimers();
//		web_view.stopLoading();
		web_view.loadData("<a></a>", "text/html", "utf-8");
		
		super.finish();

	}
	
//	@Override
//	public void onConfigurationChanged(Configuration newConfig) {
//		if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
//			setContentView(R.layout.webview);
//			//横屏
//			} else {
//			setContentView(R.layout.webview);//竖屏
//			}
//		super.onConfigurationChanged(newConfig);
//	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		return super.dispatchTouchEvent(ev);
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		 gestureScanner.onTouchEvent(event);   
		return super.onTouchEvent(event);
	}
	
	
	@Override
	public boolean onDown(MotionEvent arg0) {
		return false;
	}
	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		return false;
	}
	@Override
	public void onLongPress(MotionEvent arg0) {
		
	}
	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		return false;
	}
	@Override
	public void onShowPress(MotionEvent arg0) {
		
	}
	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		return false;
	}
}
